<template>
  <div class="todo-form-page">
    <div class="page-header">
      <div class="header-left">
        <el-button :icon="ArrowLeft" @click="handleBack" type="text" size="large"/>

        <el-input ref="titleInputRef" v-model="form.title" placeholder="请输入待办事项标题" maxlength="100"
                  show-word-limit :autofocus="!isEditMode" size="large" style="flex: 1;"/>

        <el-button type="primary" @click="handleSubmit" :loading="loading" size="large">
          {{ isEditMode ? '保存' : '新增' }}
        </el-button>
      </div>
    </div>

    <div class="form-container" v-loading="pageLoading">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" @submit.prevent="handleSubmit"
               class="todo-form">
        <el-row :gutter="16">
          <el-col :span="isEditMode ? 8 : 12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="选择优先级" style="width: 100%">
                <el-option
                    v-for="priority in priorityOptions"
                    :key="priority.value"
                    :label="priority.label"
                    :value="priority.value"
                >
                  <div class="priority-option">
                    <el-tag :type="priority.type" size="small">
                      {{ priority.label }}
                    </el-tag>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="isEditMode ? 8 : 12">
            <el-form-item label="分类" prop="categoryId">
              <el-tree-select
                v-model="form.categoryId"
                :data="categories"
                placeholder="选择分类（可选）"
                clearable
                :render-after-expand="false"
                :default-expand-all="true"
                check-strictly="true"
                style="width: 100%"
                node-key="id"
                :props="{ label: 'name', children: 'children' }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="isEditMode">
            <el-form-item label="状态" prop="status">
              <el-select v-model="(form as UpdateTodoRequest).status" placeholder="选择状态" style="width: 100%">
                <el-option
                    v-for="status in statusOptions"
                    :key="status.value"
                    :label="status.label"
                    :value="status.value"
                >
                  <div class="status-option">
                    <el-tag :type="status.type" size="small">
                      {{ status.label }}
                    </el-tag>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="标签" prop="tags">
          <el-select
              v-model="form.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="输入或选择标签（可选）"
              style="width: 100%"
          >
            <el-option
                v-for="tag in commonTags"
                :key="tag"
                :label="tag"
                :value="tag"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="截止日期" prop="dueDate">
          <el-date-picker
              v-model="form.dueDate"
              type="datetime"
              placeholder="选择截止日期（可选）"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="disabledDate"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
              v-model="form.content"
              type="textarea"
              placeholder="请输入待办内容（可选）"
              :rows="25"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, nextTick, computed} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {ElMessage, type FormInstance, type FormRules} from 'element-plus'
import {ArrowLeft} from '@element-plus/icons-vue'
import type {CreateTodoRequest, UpdateTodoRequest} from '../types'
import {TodoPriority, TodoStatus} from '../types'
import {useTodos} from '../composables'
import {todoApi} from '../api'

const router = useRouter()
const route = useRoute()

// 使用待办事项管理
const {
  categories,
  createTodo,
  updateTodo,
  loadCategories
} = useTodos()

// 表单引用和状态
const formRef = ref<FormInstance>()
const titleInputRef = ref()
const loading = ref(false)
const pageLoading = ref(false)

// 判断是否为编辑模式
const isEditMode = computed(() => !!route.params.id)
const todoId = ref<string>('')

// 表单数据
const form = ref<CreateTodoRequest | UpdateTodoRequest>({
  title: '',
  content: '',
  priority: TodoPriority.MEDIUM,
  categoryId: undefined,
  tags: [],
  dueDate: '',
  ...(isEditMode.value && {status: TodoStatus.TODO})
})

// 表单验证规则
const rules: FormRules = {
  title: [
    {max: 100, message: '标题长度不能超过100个字符', trigger: 'blur'}
  ],
  priority: [
    {required: true, message: '请选择优先级', trigger: 'change'}
  ],
  ...(isEditMode.value && {
    status: [
      {required: true, message: '请选择状态', trigger: 'change'}
    ]
  })
}

// 状态选项（仅编辑模式显示）
const statusOptions = [
  {label: '待处理', value: TodoStatus.TODO, type: 'info'},
  {label: '进行中', value: TodoStatus.IN_PROGRESS, type: 'warning'},
  {label: '已完成', value: TodoStatus.COMPLETED, type: 'success'},
  {label: '已取消', value: TodoStatus.CANCELLED, type: 'danger'}
]

// 优先级选项
const priorityOptions = [
  {label: '紧急', value: TodoPriority.URGENT, type: 'danger'},
  {label: '高', value: TodoPriority.HIGH, type: 'warning'},
  {label: '中', value: TodoPriority.MEDIUM, type: 'primary'},
  {label: '低', value: TodoPriority.LOW, type: 'info'}
]

// 常用标签
const commonTags = [
  '工作', '学习', '生活', '紧急', '重要', '日常',
  '项目', '会议', '文档', '代码', '测试', '部署'
]

// 禁用过去的日期
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

// 加载待办详情（编辑模式）
const loadTodoDetail = async (id: string) => {
  try {
    pageLoading.value = true
    const todo = await todoApi.getById(id)

    // 填充表单数据
    form.value = {
      title: todo.title,
      content: todo.content || '',
      status: todo.status,
      priority: todo.priority,
      categoryId: todo.categoryId || undefined,
      tags: todo.tags || [],
      dueDate: todo.dueDate || ''
    }
  } catch (error) {
    ElMessage.error('加载待办事项失败：' + (error as Error).message)
    router.push({
      path: '/todo',
      query: route.query  // 保持当前所有查询参数
    })
  } finally {
    pageLoading.value = false
  }
}

// 处理返回
const handleBack = () => {
  router.push({
    path: '/todo',
    query: route.query  // 保持当前所有查询参数
  })
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    // 准备提交数据
    const submitData = {
      ...form.value,
      // 清理空值
      content: form.value.content || undefined,
      categoryId: form.value.categoryId || undefined,
      tags: form.value.tags?.length ? form.value.tags : undefined,
      dueDate: form.value.dueDate || undefined
    }

    if (isEditMode.value) {
      // 编辑模式
      await updateTodo(todoId.value, submitData as UpdateTodoRequest)
      ElMessage.success('待办事项更新成功')
    } else {
      // 新建模式
      await createTodo(submitData as CreateTodoRequest)
      ElMessage.success('待办事项创建成功')
    }

    router.push({
      path: '/todo',
      query: route.query  // 保持当前所有查询参数
    })
  } catch (error) {
    ElMessage.error((isEditMode.value ? '更新' : '创建') + '失败：' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

// 页面初始化
onMounted(async () => {
  // 加载分类
  await loadCategories()

  if (isEditMode.value) {
    // 编辑模式：获取路由参数中的ID并加载待办详情
    const id = route.params.id as string
    if (!id) {
      ElMessage.error('无效的待办事项ID')
      router.push({
        path: '/todo',
        query: route.query  // 保持当前所有查询参数
      })
      return
    }

    todoId.value = id
    await loadTodoDetail(id)
  } else {
    // 新建模式：处理路由查询参数中的分类ID
    const categoryId = route.query.categoryId as string
    if (categoryId && categoryId !== '-1') {
      form.value.categoryId = categoryId
    }

    // 自动焦点到标题输入框
    await nextTick()
    setTimeout(() => {
      if (titleInputRef.value && typeof titleInputRef.value.focus === 'function') {
        titleInputRef.value.focus()
      }
    }, 100)
  }
})
</script>

<style scoped>
.todo-form-page {
  padding: 1rem;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
  width: 100%;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
}

.form-container {
  padding: 1rem;
}

.status-option,
.priority-option {
  display: flex;
  align-items: center;
}


.form-actions {
  margin-top: 32px;
  text-align: right;
}

.form-actions .el-form-item__content {
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

:deep(.el-textarea__inner) {
  resize: vertical;
}

:deep(.el-input__inner) {
  border-radius: 8px;
}

:deep(.el-select) {
  border-radius: 8px;
}

:deep(.el-button) {
  border-radius: 8px;
  padding: 12px 24px;
}

@media (max-width: 768px) {
  .form-container {
    padding: 24px 16px;
  }

  .todo-form {
    max-width: 100%;
  }

  .page-title {
    font-size: 20px;
  }
}
</style>